import http from 'http';
import url from 'url';

export default ({ port = 0, host = '127.0.0.1', requestListeners } = {}) => {
  const server = http.createServer((req, res) => {
    const uri = url.parse(req.url);
    const fn = requestListeners[uri.pathname];
    if (fn) {
      try {
        fn(uri, res, req);
      } catch (error) {
        res.end();
      }
    } else {
      res.end();
    }
  });
  server.on('clientError', (err, socket) => {
    socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
  });
  server.listen(port, host);
  return server;
};
